import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const STATEMENT_BASE = "/system/settlement/statement";

export const STATEMENT_STATUS_MAP: Record<number, string> = {
  0: "草稿",
  1: "确认中",
  2: "待开票",
  3: "待打款",
  4: "已支付"
};

export const STATEMENT_STATUS_OPTIONS = [
  { label: "草稿", value: 0 },
  { label: "确认中", value: 1 },
  { label: "待开票", value: 2 },
  { label: "待打款", value: 3 },
  { label: "已支付", value: 4 }
];

export interface StatementFilterParams {
  page?: number;
  page_size?: number;
  seller_org_id?: number | string;
  status?: number | string;
  keyword?: string;
  period_start?: string;
  period_end?: string;
}

export interface StatementItem {
  order_id: number;
  order_no: string;
  order_amount: number;
  refund_amount: number;
  commission_amount: number;
  net_amount: number;
  status?: number;
  remark?: string;
}

export interface InvoiceItem {
  id: number;
  invoice_no: string;
  invoice_type: string;
  amount: number;
  tax_rate: number | null;
  tax_amount: number | null;
  status: number;
  status_label?: string;
  submitted_at?: string | null;
  reviewed_at?: string | null;
  reviewer_id?: number | null;
  reject_reason?: string | null;
}

export interface PayoutItem {
  id: number;
  payout_no: string;
  amount: number;
  currency: string;
  pay_method: string;
  pay_account: string;
  status: number;
  status_label?: string;
  scheduled_at?: string | null;
  paid_at?: string | null;
  remark?: string | null;
}

export interface StatementListItem {
  id: number;
  statement_no: string;
  seller_org_id: number;
  seller_org_name: string;
  period_start: string;
  period_end: string;
  total_order_amount: number;
  total_refund_amount: number;
  commission_amount: number;
  payable_amount: number;
  paid_amount: number;
  status: number;
  status_label: string;
  generated_at?: string;
  confirmed_at?: string | null;
  invoiced_at?: string | null;
  paid_at?: string | null;
  remark?: string | null;
}

export interface StatementDetail extends StatementListItem {
  items: StatementItem[];
  invoices: InvoiceItem[];
  payouts: PayoutItem[];
}

const mapStatement = (item: Record<string, any>): StatementListItem => {
  const org = item.org;
  return {
    id: toNumber(item.id, 0),
    statement_no: item.statement_no ?? "",
    seller_org_id: toNumber(item.seller_org_id, 0),
    seller_org_name:
      org?.name ??
      item.seller_org_name ??
      (item.seller_org_id ? `组织 ${item.seller_org_id}` : ""),
    period_start: item.period_start ?? "",
    period_end: item.period_end ?? "",
    total_order_amount: Number(item.total_order_amount ?? 0),
    total_refund_amount: Number(item.total_refund_amount ?? 0),
    commission_amount: Number(item.commission_amount ?? 0),
    payable_amount: Number(item.payable_amount ?? 0),
    paid_amount: Number(item.paid_amount ?? 0),
    status: toNumber(item.status, 0),
    status_label:
      item.status_label ?? STATEMENT_STATUS_MAP[toNumber(item.status, 0)] ?? "",
    generated_at: item.generated_at ?? item.create_time ?? "",
    confirmed_at: item.confirmed_at ?? null,
    invoiced_at: item.invoiced_at ?? null,
    paid_at: item.paid_at ?? null,
    remark: item.remark ?? ""
  };
};

const mapDetail = (item: Record<string, any>): StatementDetail => {
  const base = mapStatement(item);
  const mapAmount = (value: any): number => Number(value ?? 0);

  const items = ensureArray<Record<string, any>>(item.items ?? []).map(row => ({
    order_id: toNumber(row.order_id, 0),
    order_no: row.order_no ?? "",
    order_amount: mapAmount(row.order_amount),
    refund_amount: mapAmount(row.refund_amount),
    commission_amount: mapAmount(row.commission_amount),
    net_amount: mapAmount(row.net_amount),
    status: toNumber(row.status ?? 1, 1),
    remark: row.remark ?? ""
  }));

  const invoices = ensureArray<Record<string, any>>(item.invoices ?? []).map(
    invoice => ({
      id: toNumber(invoice.id, 0),
      invoice_no: invoice.invoice_no ?? "",
      invoice_type: invoice.invoice_type ?? "",
      amount: mapAmount(invoice.amount),
      tax_rate:
        invoice.tax_rate !== undefined && invoice.tax_rate !== null
          ? Number(invoice.tax_rate)
          : null,
      tax_amount:
        invoice.tax_amount !== undefined && invoice.tax_amount !== null
          ? Number(invoice.tax_amount)
          : null,
      status: toNumber(invoice.status ?? 0, 0),
      status_label: invoice.status_label ?? "",
      submitted_at: invoice.submitted_at ?? invoice.create_time ?? null,
      reviewed_at: invoice.reviewed_at ?? null,
      reviewer_id:
        invoice.reviewer_id !== null
          ? toNumber(invoice.reviewer_id, null)
          : null,
      reject_reason: invoice.reject_reason ?? null
    })
  );

  const payouts = ensureArray<Record<string, any>>(item.payouts ?? []).map(
    payout => ({
      id: toNumber(payout.id, 0),
      payout_no: payout.payout_no ?? "",
      amount: mapAmount(payout.amount),
      currency: payout.currency ?? "CNY",
      pay_method: payout.pay_method ?? "",
      pay_account: payout.pay_account ?? "",
      status: toNumber(payout.status ?? 0, 0),
      status_label: payout.status_label ?? "",
      scheduled_at: payout.scheduled_at ?? null,
      paid_at: payout.paid_at ?? null,
      remark: payout.remark ?? null
    })
  );

  return {
    ...base,
    items,
    invoices,
    payouts
  };
};

export interface StatementListResult {
  list: StatementListItem[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
}

export const fetchStatementList = async (
  params: StatementFilterParams = {}
): Promise<StatementListResult> => {
  const page = toNumber(params.page, 1);
  const pageSize = toNumber(params.page_size, 10);
  const response = await http.request<ApiResponse<any>>("get", STATEMENT_BASE, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (response?.data ?? {}) as Record<string, any>;
  const list = ensureArray<Record<string, any>>(payload.list ?? []).map(
    mapStatement
  );
  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination
  };
};

export const getStatementDetail = async (
  id: number | string
): Promise<StatementDetail> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${STATEMENT_BASE}/${id}`
  );
  return mapDetail(res.data ?? {});
};

export interface StatementGeneratePayload {
  seller_org_id: number;
  period_start: string;
  period_end: string;
  order_ids?: Array<number>;
  remark?: string;
}

export const generateStatement = async (
  payload: StatementGeneratePayload
): Promise<StatementDetail> => {
  const res = await http.request<ApiResponse<any>>("post", STATEMENT_BASE, {
    data: payload
  });
  return mapDetail(res.data ?? {});
};

export const updateStatement = async (
  id: number | string,
  payload: Record<string, any>
): Promise<StatementDetail> => {
  const res = await http.request<ApiResponse<any>>(
    "put",
    `${STATEMENT_BASE}/${id}`,
    {
      data: payload
    }
  );
  return mapDetail(res.data ?? {});
};
